<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <span><i class="el-icon-first-aid-kit"></i> 护士站 - 在院病人列表 (住院列表)</span>
      </div>
    </template>

<!--    <el-form :inline="true" :model="searchForm" @submit.prevent="handleSearch">-->
<!--      <el-form-item label="病人姓名">-->
<!--        <el-input v-model="searchForm.patientName" placeholder="输入病人姓名"></el-input>-->
<!--      </el-form-item>-->
<!--      <el-form-item label="病床号">-->
<!--        <el-input v-model="searchForm.bedNo" placeholder="输入病床号"></el-input>-->
<!--      </el-form-item>-->
<!--      <el-form-item>-->
<!--        <el-button type="primary" @click="handleSearch">查询</el-button>-->
<!--        <el-button @click="handleReset">重置</el-button>-->
<!--      </el-form-item>-->
<!--    </el-form>-->

    <el-table :data="tableData" v-loading="loading" style="width: 100%">
      <el-table-column prop="patientName" label="病人姓名" width="100" />
      <el-table-column prop="age" label="年龄" width="80" />
      <el-table-column prop="gender" label="性别" width="60">
        <template #default="scope">
          <div v-if="scope.row.gender === 1">{{"男"}}</div>
          <div v-else-if="scope.row.gender === 2">{{"女"}}</div>
          <div v-else>{{"未知"}}</div>
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="电话" width="120" />
      <el-table-column prop="roomName" label="科室" width="150" />
      <el-table-column prop="wardNo" label="病房号" width="100" />
      <el-table-column prop="bedNo" label="病床号" width="100" />
      <el-table-column prop="doctorName" label="主治医生" width="120" />
      <el-table-column prop="oaDate" label="入院时间" width="180" />
      <el-table-column label="操作" fixed="right" min-width="300">
        <template #default="scope">
          <el-button size="small" type="primary" @click="handleViewOrders(scope.row)">查看医嘱</el-button>
          <el-button size="small" type="success" @click="handleAddRecord(scope.row)">添加护理</el-button>
          <el-button size="small" @click="handleViewRecords(scope.row)">护理记录</el-button>
          <el-button
              v-if="scope.row.status === 1"
              size="small"
              type="danger"
              @click="handleProcessDischarge(scope.row)"
          >
            办理出院
          </el-button>
        </template>
      </el-table-column>
    </el-table>

<!--    <el-pagination-->
<!--        style="margin-top: 20px;"-->
<!--        v-model:current-page="pagination.pageNum"-->
<!--        v-model:page-size="pagination.pageSize"-->
<!--        :page-sizes="[10, 20, 50, 100]"-->
<!--        layout="total, sizes, prev, pager, next, jumper"-->
<!--        :total="pagination.total"-->
<!--        @size-change="handleSizeChange"-->
<!--        @current-change="handlePageChange"-->
<!--    />-->
  </el-card>

  <el-dialog v-model="dialogOrdersVisible" title="查看医嘱" width="60%">
    <p>病人: <strong>{{ currentPatient.patientName }}</strong> (病床: {{ currentPatient.bedNo }})</p>
    <el-table :data="ordersData" max-height="400">
      <el-table-column prop="content" label="医嘱内容" />
      <el-table-column prop="doctorName" label="开立医生" width="120" />
      <el-table-column prop="nurseName" label="执行护士" width="120" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === 0 ? 'warning' : 'success'">
            {{ scope.row.status === 0 ? '待执行' : '已执行' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120">
        <template #default="scope">
          <el-button
              v-if="scope.row.status === 0"
              size="small"
              type="primary"
              @click="handleExecuteOrder(scope.row.id)"
          >
            执行医嘱
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <el-button @click="dialogOrdersVisible = false">关闭</el-button>
    </template>
  </el-dialog>

  <el-dialog v-model="dialogAddRecordVisible" title="添加护理记录" width="50%">
    <p>病人: <strong>{{ currentPatient.patientName }}</strong> (病床: {{ currentPatient.bedNo }})</p>
    <el-form :model="newRecordForm" label-width="80px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="体温(℃)">
            <el-input v-model="newRecordForm.nrTemperature" placeholder="例如: 36.8"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="心率(bpm)">
            <el-input v-model="newRecordForm.nrPulse" placeholder="例如: 75"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="血压(mmHg)">
        <el-input v-model="newRecordForm.nrBloodpressure" placeholder="例如: 120/80"></el-input>
      </el-form-item>
      <el-form-item label="护理内容">
        <el-input
            type="textarea"
            :rows="4"
            v-model="newRecordForm.nrContent"
            placeholder="输入护理内容...">
        </el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogAddRecordVisible = false">取消</el-button>
      <el-button type="primary" @click="submitNewRecord">提交</el-button>
    </template>
  </el-dialog>

  <el-dialog v-model="dialogViewRecordsVisible" title="查看护理记录" width="50%">
    <p>病人: <strong>{{ currentPatient.patientName }}</strong> (病床: {{ currentPatient.bedNo }})</p>
    <el-timeline style="max-height: 500px; overflow-y: auto; padding-top: 10px;">
      <el-timeline-item
          v-for="record in recordsData"
          :key="record.id"
          :timestamp="record.timestamp"
      >
        <p><strong>护士: {{ record.nurseName }}</strong></p>
        <p>体征: 体温 {{ record.temperature }}℃, 血压 {{ record.bloodPressure }}mmHg, 心率 {{ record.pulse }}bpm</p>
        <p>内容: {{ record.content }}</p>
      </el-timeline-item>
    </el-timeline>
    <template #footer>
      <el-button @click="dialogViewRecordsVisible = false">关闭</el-button>
    </template>
  </el-dialog>

</template>

<script>
// 引入 Element Plus 的消息提示和确认框
import { ElMessage, ElMessageBox } from 'element-plus';
import {queryAll} from "../api/inpatient.js";
import {queryByPatientId} from "../api/doctorOrder.js";
import {queryRecordsByPatientId} from "../api/nursingRecord.js";

// 模拟API调用的函数
const fetchOrdersApi = (patientId) => {
  console.log("查询病人医嘱:", patientId);
  return new Promise(resolve => {
    const orders = [
      { id: 201, content: '一级护理，测量T/P/R Q4H', doctorName: '李秀英', status: 1 },
      { id: 202, content: '明日行[膝关节镜手术]，NPO 8H', doctorName: '李秀英', status: 0 },
      { id: 203, content: '低盐低脂饮食，监测血压 Q4H', doctorName: '王建国', status: 1 },
    ];
    resolve(orders.filter(o => (patientId % 3) + 1 === (o.id % 3) + 1)); // 模拟不同病人的医嘱
  });
};

const executeOrderApi = (orderId) => {
  console.log("执行医嘱ID:", orderId);
  return new Promise(resolve => setTimeout(resolve, 300));
};

const addNursingRecordApi = (record) => {
  console.log("提交护理记录:", record);
  return new Promise(resolve => setTimeout(resolve, 500));
};

const fetchNursingRecordsApi = (patientId) => {
  console.log("查询护理记录:", patientId);
  return new Promise(resolve => {
    const records = [
      { id: 301, timestamp: '2025-10-30 14:00', nurseName: '周芳', temperature: '37.1', bloodPressure: '125/80', pulse: 78, content: '[医嘱1] 已执行。患者生命体征平稳。' },
      { id: 302, timestamp: '2025-10-30 10:00', nurseName: '周芳', temperature: '37.0', bloodPressure: '120/80', pulse: 75, content: '入院护理评估已完成。' },
    ];
    resolve(records);
  });
};

const processDischargeApi = (patientId) => {
  console.log("办理出院:", patientId);
  return new Promise(resolve => setTimeout(resolve, 500));
};

export default {
  name: "InpatientNurseStation",
  // 1. 使用 data() 选项
  data() {
    return {
      // 搜索表单
      searchForm: {
        patientName: '',
        bedNo: ''
      },
      // 表格数据
      tableData: [
        {
          "id": 1,
          "patientId": 3,
          "patientName": "刘强",
          "age": 37,
          "gender": 1,
          "phone": "13712345678",
          "bedNo": "B0801",
          "wardNo": "B08-骨外科病区",
          "roomName": "骨外科",
          "doctorName": "李秀英",
          "oaDate": "2025-10-29"
        }
      ],
      loading: false,
      // 分页
      pagination: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      // 弹窗可见性
      dialogOrdersVisible: false,
      dialogAddRecordVisible: false,
      dialogViewRecordsVisible: false,

      // 当前操作的病人行
      currentPatient: {},

      // 医嘱数据
      ordersData: [],

      // 护理记录数据
      recordsData: [],

      // 新增护理记录的表单
      newRecordForm: {
        nrTemperature: '',
        nrBloodpressure: '',
        nrPulse: '',
        nrContent: ''
      }
    };
  },
  // 2. 使用 methods 选项
  methods: {
    // 获取主列表数据
    async fetchData() {
      this.loading = true;
      // const query = {
      //   pageNum: this.pagination.pageNum,
      //   pageSize: this.pagination.pageSize,
      //   ...this.searchForm
      // };

      // 对应我们之前设计的 POST /.../list 接口
      let {data:data} = await queryAll();
      console.log(data)
      this.tableData = data.obj
      // this.tableData = res.list;
      // this.pagination.total = res.total;
      this.loading = false;
    },

    // 搜索
    handleSearch() {
      this.pagination.pageNum = 1; // 搜索时重置回第一页
      this.fetchData();
    },

    // 重置搜索
    handleReset() {
      this.searchForm.patientName = '';
      this.searchForm.bedNo = '';
      this.handleSearch();
    },

    // 分页：每页条数变化
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.fetchData();
    },

    // 分页：当前页码变化
    handlePageChange(val) {
      this.pagination.pageNum = val;
      this.fetchData();
    },

    // --- 核心操作方法 (对应需求文档) ---

    // 1. 查看医嘱
    async handleViewOrders(row) {
      this.currentPatient = { ...row };
      this.dialogOrdersVisible = true;
      // 请求该病人的医嘱列表
      let {data:data} = await queryByPatientId(row.patientId)
      this.ordersData = data.obj
    },

    // 2. 执行医嘱
    async handleExecuteOrder(orderId) {
      try {
        await executeOrderApi(orderId);
        ElMessage.success('医嘱执行成功!');
        // 刷新医嘱列表 (还没想好业务该业务要怎么处理)
        this.ordersData = await fetchOrdersApi(this.currentPatient.patientId);
      } catch (err) {
        ElMessage.error('执行失败');
      }
    },

    // 3. 添加护理记录 (打开弹窗)
    handleAddRecord(row) {
      this.currentPatient = { ...row };
      // 重置表单
      this.newRecordForm = {
        nrTemperature: '',
        nrBloodpressure: '',
        nrPulse: '',
        nrContent: ''
      };
      this.dialogAddRecordVisible = true;
    },

    // 4. 提交护理记录
    async submitNewRecord() {
      if (!this.newRecordForm.content) {
        ElMessage.warning('护理内容不能为空');
        return;
      }
      const record = {
        nrCaseId: this.currentPatient.patientId,
        // nurseId 会由后端自动从Token获取

        ...this.newRecordForm,
        // nursingDate: new Date().toISOString()
      };

      await addNursingRecordApi(record);
      ElMessage.success('护理记录添加成功!');
      this.dialogAddRecordVisible = false;
    },

    // 5. 查看护理记录
    async handleViewRecords(row) {
      this.currentPatient = { ...row };
      this.dialogViewRecordsVisible = true;
      // this.recordsData = await fetchNursingRecordsApi(row.patientId);
      let {data:data} = await queryRecordsByPatientId(row.patientId)
      console.log(data)
      this.recordsData = data.obj
    },

    // 6. 办理出院
    handleProcessDischarge(row) {
      ElMessageBox.confirm(
          `确定要为病人 [${row.patientName}] (病床: ${row.bedNo}) 办理出院手续吗?`,
          '办理出院确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
      ).then(async () => {
        // 调用办理出院的API
        await processDischargeApi(row.patientId);
        ElMessage.success('办理出院成功!');
        // 刷新主列表
        this.fetchData();
      }).catch(() => {
        // 用户点击了取消
      });
    }
  },
  // 3. 使用 created() 钩子
  created() {
    // 页面加载时自动获取第一页数据
    this.fetchData();
  }
};
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
}
.el-form {
  border-bottom: 1px solid var(--el-border-color-light);
  padding-bottom: 10px;
  margin-bottom: 20px;
}
.el-timeline {
  padding-left: 10px; /* 修复Timeline的默认内边距 */
}
</style>